package com.chen.auth.listener;

import cn.hutool.core.collection.CollUtil;
import com.chen.auth.handler.AuthenticationSuccessEventHandler;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.security.authentication.event.AuthenticationSuccessEvent;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @description: 登录成功事件监听器
 * @Author C_Y_J
 * @create 2022/1/13 16:36
 **/
@Component
@Slf4j
public class AuthenticationSuccessEventListener implements ApplicationListener<AuthenticationSuccessEvent> {

    @Resource
    AuthenticationSuccessEventHandler authenticationSuccessEventHandler;

    @SneakyThrows
    @Override
    public void onApplicationEvent(AuthenticationSuccessEvent event) {
        Authentication authentication = (Authentication) event.getSource();
        // 是认证用户，从请求上下文中拿到请求属性
        if (isUserAuthentication(authentication)) {

            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = requestAttributes.getRequest();
            HttpServletResponse response = requestAttributes.getResponse();

            // 调用自定义业务实现
            authenticationSuccessEventHandler.handler(request, response,authentication);
        }
    }

    private boolean isUserAuthentication(Authentication authentication) {
        return authentication.getPrincipal() instanceof UserDetails && CollUtil.isNotEmpty(authentication.getAuthorities());
    }

}
